<template>
  <div class="account-settings">
    <h2 class="title">账号设置</h2>

    <div class="settings-container">
      <!-- 绑定微信 -->
      <div class="setting-item">
        <div class="label">学员姓名</div>
        <div class="value marT10">
          <div class="flex flex-align-center">
            <span>{{ storeInfo.memberName }}</span>
          </div>
        </div>
      </div>

      <!-- 手机号 -->
      <div class="setting-item">
        <span class="label">手机号</span>
        <div class="value marT10">
          <span>+86 {{ storeInfo.mobile }}</span>
        </div>
      </div>

      <!-- 登录密码 -->
      <div class="setting-item">
        <span class="label">登录密码</span>
        <div class="value marT10">
          <span>**********</span>
          <div class="action-btn" @click="passDialogVisible = true">去修改</div>
        </div>
      </div>

      <!-- 头像 -->
      <div class="setting-item">
        <span class="label">头像：</span>
        <div class="value marT10">
          <img :src="storeInfo.avatar" alt="" class="avatar" />
          <!-- <div class="action-btn" @click="handleUploadAvatar">去上传</div> -->
          <el-upload class="avatar-uploader" :action="server" :headers="headers" :show-file-list="false"
            :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
            <div class="action-btn">去上传</div>
          </el-upload>
        </div>
      </div>
    </div>
    <button class="back-btn" @click="handleBack">返回</button>
    <el-dialog v-model="passDialogVisible" title="更改密码" width="20%" class="updatePass">
      <el-form ref="formRef" :model="pwdForm" :rules="rules" label-width="100px"
        style="height: 200px;margin-top: 30px;">
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="pwdForm.newPassword" type="password" show-password />
        </el-form-item>
        <el-form-item label="确认新密码" prop="confirmPassword">
          <el-input v-model="pwdForm.confirmPassword" type="password" show-password />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="passDialogVisible = false">取消</el-button>
          <el-button type="success" @click="passHandleSubmit">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import { useRouter } from 'vue-router'
import { ref, computed, onMounted, reactive } from 'vue'
import { useUserStore } from '@/store/user'
import { ElMessage } from 'element-plus'
import { getStoreInfo, resetPassword, EditUserList } from '@/api/userApi'
import type { FormRules, FormInstance } from 'element-plus'

const userStore = useUserStore()
let server = `${import.meta.env.VITE_API_URL}files`
let { accessToken } = userStore
const headers = { Authorization: 'Bearer ' + accessToken }

const router = useRouter()
const passDialogVisible = ref(false)
const pwdForm = reactive({
  newPassword: '',
  confirmPassword: ''
})

// 重复密码的验证
const validatePasswordMatch = (rule: any, value: string, callback: (error?: Error) => void) => {
  if (value !== pwdForm.newPassword) {
    callback(new Error('两次密码不一致！'))
  } else {
    callback()
  }
}

const rules = reactive<FormRules>({
  newPassword: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  confirmPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    { validator: validatePasswordMatch, trigger: 'blur' }
  ]
})

const formRef = ref<FormInstance>()
const passHandleSubmit = async () => {
  if (!formRef.value) return
  try {
    await formRef.value.validate(async (valid) => {
      if (valid) {
        try {
          const { code, data, msg } = await resetPassword(Number(userStore.storeInfo.memberId), pwdForm.newPassword)
          if (code === '00000') {
            // 这里添加修改密码的API调用
            ElMessage.success('密码修改成功')
            passDialogVisible.value = false
            pwdForm.newPassword = ''
            pwdForm.confirmPassword = ''
          } else {
            ElMessage.error(msg)
          }
        } catch (e) {
        } finally {
        }
      }
    })

  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

// 响应式数据
const wechatBind = ref(true)

const handleBack = () => {
  console.log('返回')
  router.go(-1)
  // 返回上一页
}
const handleAvatarSuccess = async (file: any) => {
  storeInfo.value.avatar = file.data.url
  const res = await EditUserList({
    id: storeInfo.value.memberId,
    avatar: storeInfo.value.avatar
  })
  if (res.code === '00000') {
    ElMessage.success('编辑成功')
    getHeadInfo()
  }
}
//上传限制大小格式等
const beforeAvatarUpload = (file: any) => {
  const isLt2M = file.size / 10240 / 10240 < 2
  if (file.type != 'image/jpeg' && file.type != 'image/png' && file.type != 'image/gif') {
    ElMessage.error('图片类型仅支持JPG/PNG/GIF格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 20MB!!')
    return false
  }
}

interface storeItem {
  storeName: string
  avatar: string
  memberName: string
  mobile: string
  memberId: number
}
const storeInfo = ref<Partial<storeItem>>({})
const getHeadInfo = async () => {
  const res = await getStoreInfo()
  if (res.code === '00000') {
    storeInfo.value = res.data
    storeInfo.value.mobile = res.data.mobile
    userStore.setStoreInfo(res.data)
  }
}
onMounted(() => {
  getHeadInfo()
})
</script>
<style scoped lang="scss">
@use "sass:math";

@function rem($px) {
  @return math.div($px, 16) * 1rem;
}

.account-settings {
  max-width: rem(800);
  margin: 0 auto;
  padding: rem(50) rem(20) rem(20);
  font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
}

.title {
  text-align: center;
  margin-bottom: rem(30);
  color: #333;
  font-size: rem(24);
}

.settings-container {
  background-color: #fff;
  padding: rem(20) 0;
  padding-top: rem(15);
}

.setting-item {
  padding: rem(25) rem(30);
  border-bottom: 1px solid #f0f0f0;
}

.setting-item:last-child {
  border-bottom: none;
}

.label {
  color: rgb(154, 158, 164);
  font-size: rem(16);
  width: rem(100);
}

.value {
  flex: 1;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.action-btn {
  color: #00c356;
  cursor: pointer;
  font-size: rem(16);
  transition: all 0.3s;
}

.avatar {
  width: rem(70);
  height: rem(70);
  border-radius: 50%;
  object-fit: cover;
  border: 1px solid #eee;
}

.back-btn {
  display: block;
  margin: rem(30) auto 0;
  padding: rem(8) rem(20);
  background-color: #fff;
  border: 1px solid #d2d2d2;
  border-radius: rem(4);
  cursor: pointer;
  transition: all 0.3s;
}

.back-btn:hover {
  background-color: #e0e0e0;
}

:deep(.el-form-item) {
  margin-bottom: rem(40) !important;
}

:deep(.el-dialog__header) {
  font-weight: bold;
}
</style>
